import wx
from modules import meide as ui

class TreeBookPanel(wx.Panel):
    def __init__(self, parent, id=-1, treewidth=150):
        wx.Panel.__init__(self, parent, id, size=wx.DefaultSize)
        
        self._id = 0
        self.last = None
        
        self.sizer = sizer = ui.HBox(namebinding='widget').create(self).auto_layout()
        sizer.add(ui.Tree(size=(treewidth, -1), style=wx.TR_HAS_BUTTONS
                               | wx.TR_LINES_AT_ROOT
                               | wx.TR_HIDE_ROOT), name='tree', flag=wx.EXPAND|wx.ALL)

        self.panels = sizer.add(ui.VBox)
        
        sizer.auto_fit(0)
        
        self.init()
        
    def get_id(self):
        self._id += 1
        return self._id
    
    def init(self):
        wx.EVT_TREE_SEL_CHANGED(self.tree, self.tree.GetId(), self.OnSelected)
        self.root = self.tree.AddRoot("The Root Item")
#        self.add_pages()
        
    def add_page(self, page, title='', parent=None):
        if not parent:
            parent = self.root
        child = self.tree.AppendItem(parent, title)
        if parent is not self.root:
            self.tree.Expand(parent)
        
        _id = self.get_id()
        name = 'page%d' % _id
        self.tree.SetPyData(child, _id)
        node = self.panels.add(page, proportion=1, flag=wx.EXPAND, name=name)
        self.panels.hide(name)
        return child
        
    def select(self, item=None):
        if not item:
            item, cookie = self.tree.GetFirstChild(self.root)
        if not self.is_ok(item): return
        self.tree.SelectItem(item)
        
    def OnSelected(self, event):
        item = event.GetItem()
        if self.last:
            self.panels.hide(self.last)
        self.last = self.show(item)
        
    def is_ok(self, item):
        return item and item.IsOk() and item is not self.root
    
    def show(self, item=None):
        if not item:
            item, cookie = self.tree.GetFirstChild(self.root)
        if not self.is_ok(item): return
        try:
            _id = self.tree.GetPyData(item)
            name = 'page%d' % _id
            self.panels.show(name)
            self.panels.layout()
            return name
        except:
            import traceback
            traceback.print_exc()
            
#    def add_pages(self):
#        for x in ('white', 'red', 'blue'):
#            child = self.add_page(ColorPanel(self, color=x), title=x)
#            for y in ('white', 'red', 'blue'):
#                last = self.add_page(ColorPanel(self, color=x), title=x, parent=child)
#  